package com.caiheng.api.controller.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.mer.Mer;
import com.caiheng.api.entity.product.Product;
import com.caiheng.api.entity.wxuser.UserCollection;
import com.caiheng.api.service.mer.MerService;
import com.caiheng.api.service.product.ProductService;
import com.caiheng.api.service.wxuser.UserCollectionService;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RestController
@RequestMapping("/user/collection")//url:模块/资源/{}/细分
public class UserCollectionController extends BaseController {

    @Resource
    private UserCollectionService userCollectionService;
    @Resource
    private ProductService productService;
    @Resource
    private MerService merService;

    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片前缀
    /**
     * 收藏商品
     * @return
     */
    @PostMapping(value = "/add")
    public JSONObject collectionSomething(@RequestBody String requestParam){
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int product_id = jsonRequest.containsKey("product_id") ? jsonRequest.getInt("product_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            //收藏的类型 0 - 商品  1 - 店铺
            int collection_type = jsonRequest.containsKey("collection_type") ? jsonRequest.getInt("collection_type") : 0;

            try{
                QueryWrapper<UserCollection> qw = new QueryWrapper<>();
                qw.eq("user_id",user_id);
                if(collection_type == 0){
                    qw.eq("product_id",product_id);
                }else{
                    qw.eq("mer_id",mer_id);
                }
                UserCollection userCollection = userCollectionService.getOne(qw);
                if(userCollection == null){
                    UserCollection collection = new UserCollection();
                    if(collection_type == 0){//商品
                        Product product = productService.getProductInfoById(product_id, 0);
                        if(product == null){
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该商品不存在"),true,true);
                        }
                        collection.setProductId(product_id);
                    }else if(collection_type == 1){//店铺
                        collection.setMerId(mer_id);
                    }
                    collection.setUserId(user_id);
                    collection.setSkuId(0);
                    collection.setCollectionType(collection_type);//0 - 商品 1 - 店铺
                    collection.setState(0);
                    boolean ret = userCollectionService.save(collection);
                    if (ret){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"收藏成功"),true,true);
                    }else{
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"收藏失败"),true,true);
                    }
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"已收藏"),true,true);
                }
            }catch (Exception ex){

            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * * 根据用户ID和收藏类型查询列表
     * @return
     */
    @PostMapping(value = "/list")
    public JSONObject getList(@RequestBody String requestParam){
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int collection_type = jsonRequest.containsKey("collection_type") ? jsonRequest.getInt("collection_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 0;

            QueryWrapper<UserCollection> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            qw.eq("collection_type",collection_type);
            List<UserCollection> list = userCollectionService.getPageEntityList(qw,pageIndex,pageSize);
            if (list!=null && list.size() > 0){
                for(UserCollection collection : list){
                    if(collection.getCollectionType() == 0){
                        Product product = productService.getProductInfoById(collection.getProductId(), 0);
                        if(product != null){
                            if(StrUtil.isNotEmpty(product.getImage())){
                                if(product.getImage().indexOf("http") < 0){
                                    collection.setImgUrl(imgPrefix + product.getImage());
                                }else{
                                    collection.setImgUrl(product.getImage());
                                }
                            }
                            collection.setProductName(product.getStoreName());
                            collection.setPrice(product.getPrice());
                            collection.setOldPrice(product.getOtPrice());
                        }
                    }else{
                        Mer mer = merService.getById(collection.getMerId());
                        if(mer!=null){
                            if(StrUtil.isNotEmpty(mer.getShopLogo())){
                                mer.setShopLogo(imgPrefix + mer.getShopLogo());
                            }
                        }
                        collection.setMer(mer);
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", list.size(), list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 删掉收藏商品
     * @return
     */
    @PostMapping(value = "/delete")
    public JSONObject delete(@RequestBody String requestParam){
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long collect_id = jsonRequest.containsKey("collect_id") ? jsonRequest.getInt("collect_id") : 0;

            UserCollection userCollection = userCollectionService.findById(collect_id);
            if(userCollection != null){
                if(userCollection.getUserId() == user_id){
                    boolean ret = userCollectionService.removeById(userCollection.getId());
                    if (ret){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"删除成功"),true,true);
                    }else{
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败"),true,true);
                    }
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该收藏不属于您"),true,true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未收藏该商品"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 判断是否已经收藏过 商家或者商品
     * @param user_id
     * @param ug_id
     * @param collection_type   收藏的类型 0 - 商品  1 - 商家
     * @return
     */
    @PostMapping(value = "/iscollect/{userId}/{ugId}/{collectionType}")
    public JSONObject isCollect(@PathVariable("userId") int user_id, @PathVariable("ugId") int ug_id, @PathVariable("collectionType") int collection_type){
        JSONObject result = null;
        try{
            QueryWrapper<UserCollection> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            if(collection_type == 0){
                qw.eq("product_id",ug_id);
            }else{
                qw.eq("mer_id",ug_id);
            }
            UserCollection userCollection = userCollectionService.getOne(qw);
            if(userCollection == null){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"未收藏"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"已收藏"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }
}
